<?php

namespace app\appapi\controller;


use app\data\model\LiveErrorLog;

class ErrorLog extends BaseController
{
    //获取应用列表
    public function setError(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        if(!isset($post['error'])) $this->error('less error');
        if(LiveErrorLog::mk()->where(['user_id'=>$userId,'error_info'=>$post['error']])->count() <= 0){
            LiveErrorLog::mk()
                ->where(['user_id'=>$userId,'error_info'=>$post['error']])
                ->inc('update_num',1)
                ->update(['update_time'=>date('Y-m-d H:i:s')]);
        }else{
            LiveErrorLog::mk()->insert([
                'user_id'=>$userId,
                'error_info'=>$post['error'],
            ]);
        }

        $this->success('成功');
    }

    //检查文件并移动文件
    private function getFilePath(){
        $upload_dir = $this->app->getRootPath().'public/errorlog/';
        $max_size = 1024 * 1024 * 10;
        $allow_exts = ['txt'];

        if (empty($_FILES['file']) || $_FILES['file']['error'] != 0) {
            //$_FILES['file'] 是空数组，检查 $_FILES['file']['error'] 是否为 0,如果为 0，表示文件上传成功。
            return ['code'=>0,'info'=>'上传失败，请稍后再试'];
        }
        $temp_file = $_FILES['file']['tmp_name'];
        $file_name = $_FILES['file']['name'];//原文件名

        if(!file_exists($temp_file)){
            return ['code'=>0,'info'=>'文件【'.$temp_file."】不存在"];
        }
        $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
        if (!in_array($file_ext, $allow_exts)) {
            return ['code'=>0,'info'=>'文件类型不符合要求，请上传txt、docx类型文件'];
        }
        if ($_FILES['file']['size'] > $max_size) {
            return ['code'=>0,'info'=>'文件大小不能超过5MB，请重新上传'];
        }
        if (!is_uploaded_file($temp_file)) {
            return ['code'=>0,'info'=>'非法上传，请重新上传'];
        }
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir);
        }
        $new_file_name = time().'-'.rand(100000, 999999).'.'.$file_ext;

        move_uploaded_file($temp_file, $upload_dir . $new_file_name);
        return [
            'code'      =>1,
            'path'      =>$upload_dir . $new_file_name,
            'url'       =>$this->request->domain().'/errorlog/'.$new_file_name,
            'file_name' =>$file_name,
            'file_ext'  =>$file_ext
        ];
    }
}